import fs from "fs";
import path from "path";
import { fileURLToPath } from "url";

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const ROOT = path.resolve(__dirname, "../../");
const DATA_DIR = path.join(ROOT, "data");

function ensureDir(p) {
  if (!fs.existsSync(p)) fs.mkdirSync(p, { recursive: true });
}

function readJson(file, fallback) {
  ensureDir(DATA_DIR);
  const full = path.join(DATA_DIR, file);
  if (!fs.existsSync(full)) {
    if (fallback !== undefined) {
      fs.writeFileSync(full, JSON.stringify(fallback, null, 2), "utf-8");
      return fallback;
    }
    return null;
  }
  const raw = fs.readFileSync(full, "utf-8");
  try {
    return raw.trim() ? JSON.parse(raw) : fallback ?? null;
  } catch {
    return fallback ?? null;
  }
}

function writeJson(file, data) {
  ensureDir(DATA_DIR);
  const full = path.join(DATA_DIR, file);
  fs.writeFileSync(full, JSON.stringify(data, null, 2), "utf-8");
}

export const db = {
  readJson,
  writeJson,
  DATA_DIR
};